﻿<?php
include("../config/config.inc.php");

/*导入QQ用户*/
class CImportQQUser
{
	/* 构造函数 */
	function __construct(){
		$lock = dirname(__FILE__) . "/../lock/importqq";
		$fp = fopen($lock, "w");
		if( !$fp ){
			return;
		}
		if( !flock($fp, LOCK_EX | LOCK_NB) ){
			return;
		}
		// 开始导入
		$this->StartImport();
		
		flock($fp, LOCK_UN);
		fclose($fp);
	}
	/* 开始导入 */
	function StartImport(){
		global $mysql_server, $mysql_user, $mysql_passwd, $mysql_database;
		global $qqsql_server, $qqsql_user, $qqsql_passwd, $qqsql_database;
		
		$mysql = mysql_connect($mysql_server, $mysql_user, $mysql_passwd);
		$qqsql = mssql_connect($qqsql_server, $qqsql_user, $qqsql_passwd);
		if( !$mysql || !$qqsql || !mysql_select_db($mysql_database, $mysql)
			|| !mssql_select_db($qqsql_database, $qqsql) ){
			mysql_close($mysql);
			mssql_close($qqsql);
			return;
		}
		/*导入数据*/
		$this->ImportData($mysql, $qqsql);
		
		mysql_close($mysql);
		mssql_close($qqsql);
	}
	/*导入数据*/
	function ImportData($mysql, $qqsql){
		if( !mssql_query("if not (select object_id('Tempdb..#t_mysql_qq')) is null drop table #t_mysql_qq", $qqsql) )
			return;
		if( !mssql_query("create table #t_mysql_qq (qq nvarchar(20) primary key)", $qqsql) )
			return;
		// 把数据导入临时表中
		for($i = 0; true; $i++){
			$start = $i * 1000;
			// 将未导入的数据导入
			$res1 = mysql_query("select qq from t_user_qq2 limit {$start}, 1000", $mysql);
			if(mysql_num_rows($res1) < 1) break;
			while( $row1 = mysql_fetch_row($res1) ){
				mssql_query("insert into #t_mysql_qq(qq) values('{$row1[0]}')", $qqsql);
			}
			mysql_free_result($res1);			
		}
		// 查询未导入之数据
		for($i = 0; true; $i++){
			$sql = "select top 1000 qq, qqName, convert(varchar(20),createTime,120) from T_qq_account where "
				. " qq not in (select qq from #t_mysql_qq)";
			$res2 = mssql_query($sql, $qqsql);
			if(mssql_num_rows($res2) < 1) break;
			while( $row2 = mssql_fetch_row($res2) ){
				$name = str_replace("'", "''", iconv("gb2312", "utf-8", $row2[1]));
				$sql = "insert into t_user_qq2(qq,name,fistdt,email) values('{$row2[0]}', '{$name}', '{$row2[2]}', '{$row2[0]}@qq.com')";
				mysql_query($sql, $mysql);
				mssql_query("insert into #t_mysql_qq(qq) values('{$row2[0]}')", $qqsql);
			}
			mssql_free_result($res2);
		}
	}
}

ignore_user_abort(true);
set_time_limit(0);
/*发送邮件操作*/
$cc = new CImportQQUser();
?>